<template>
  <div class="order_detail_wrapper">
    <el-main v-loading="loading">
      <el-card class="mt10">
        <div class="clearfix">
          <span style="font-size: 16px;font-weight: bold">订单详情</span>
          <el-button style="float: right;" size="small" @click="$router.back()">返回</el-button>
        </div>
      </el-card>
      <template v-if="orderDetail.orderType === 'PLAN'">
        <el-card class="mt10">
          <el-descriptions
            title="基本信息"
            :column="2"
            border
            label-class-name="my-label"
            contentClassName="my-content">
            <el-descriptions-item label="订单ID">{{ orderDetail.orderId }}</el-descriptions-item>
            <el-descriptions-item label="订单类型">计划订单</el-descriptions-item>
            <el-descriptions-item label="下单手机号">{{ orderDetail.orderPhone }}</el-descriptions-item>
            <el-descriptions-item label="下单UID">{{ orderDetail.userId }}</el-descriptions-item>
            <el-descriptions-item label="下单时间">{{ timeFormat(orderDetail.placeOrderTime, '') }}</el-descriptions-item>
            <el-descriptions-item label="订单内容">{{ orderDetail.productName }}</el-descriptions-item>
            <el-descriptions-item label="订单状态">{{ orderDetail.orderStatusDesc }}</el-descriptions-item>
            <el-descriptions-item />
          </el-descriptions>
        </el-card>
        <el-card class="mt10">
          <el-descriptions title="计划信息" />
          <div class="vertical">
            <el-descriptions :column="2" border label-class-name="my-label" contentClassName="my-content">
              <el-descriptions-item label="计划ID">{{ orderDetail.planInfoPojo.id }}</el-descriptions-item>
              <el-descriptions-item label="计划时长">{{ orderDetail.planInfoPojo.periodStr }}</el-descriptions-item>
              <el-descriptions-item label="计划周期">{{ `${orderDetail.planInfoPojo.deliveryDateFirst} ~ ${orderDetail.planInfoPojo.deliveryDateFinal}`}}</el-descriptions-item>
              <el-descriptions-item label="配送频次">{{ orderDetail.planInfoPojo.deliveryPeriodStr }}</el-descriptions-item>
              <el-descriptions-item label="期数">{{ orderDetail.planInfoPojo.deliveryTimes }}期</el-descriptions-item>
              <el-descriptions-item />
            </el-descriptions>
            <el-descriptions :column="2" v-for="item in addressPlanArr" :key="item.id" border label-class-name="my-label" contentClassName="my-content">
              <el-descriptions-item :label="`第${numberToChinese(item.termNumber)}期编号`">{{ `${orderDetail.planInfoPojo.planNo}-${item.termNumber}` }}</el-descriptions-item>
              <el-descriptions-item label="配送商品">{{ setShippingProductsFn(item.shippingProducts) }}</el-descriptions-item>
              <!-- 待支付、已取消、已退款的显示-- -->
              <el-descriptions-item label="发货时间">{{ `${orderDetail.orderStatus === 'PENDING_PAYMWENT' || orderDetail.orderStatus === 'UNFINISHED_PAYMENT_CANCEL' || orderDetail.orderStatus === 'CANCEL_BEFORE_SHIPMENT' || orderDetail.orderStatus === 'GROUP_ORDER_FAIL_CANCLE' || orderDetail.orderStatus === 'CANCELED' || orderDetail.orderStatus === 'CANCELED_REFUNDED' || orderDetail.orderStatus === 'REFUNDED' ? '--' : timeFormat(item.deliveryTime, '')}`}}</el-descriptions-item>
              <el-descriptions-item label="预计发货时间">{{ timeFormat(item.planDeliveryTime, '') }}</el-descriptions-item>
              <el-descriptions-item label="运单号">{{ setshippingNoFn(item.shippingWaybills) }}</el-descriptions-item>
              <el-descriptions-item label="物流公司">{{ item.shippingCompany }}</el-descriptions-item>
              <el-descriptions-item label="收货地址">{{ item.deliveryAddress }}</el-descriptions-item>
              <el-descriptions-item label="联系人">{{ item.deliveryName }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{ item.contactNumber }}</el-descriptions-item>
              <el-descriptions-item label="操作">
                <el-button
                  size="mini"
                  type="primary"
                  :disabled="item.shippingStatus !== 'PENDING_SHIPMENT'"
                  @click="handleDelivery(item.id)">发货</el-button>
                <el-button
                  size="mini"
                  type="primary"
                  :disabled="disabledRefundStatus.includes(item.shippingStatus)"
                  @click="handleRefund(item.orderId)">退款</el-button>
                <el-button
                  size="mini"
                  type="primary"
                  :disabled="checkPrint(item)"
                  @click="handlePrint(item.id)">打印</el-button>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
        <el-card class="mt10">
          <el-descriptions
            title="交易信息"
            :column="2"
            border
            size="small"
            label-class-name="my-label"
            contentClassName="my-content">
            <el-descriptions-item label="原价">{{ orderDetail.productPrice }}</el-descriptions-item>
            <el-descriptions-item label="计划减免">{{ orderDetail.planDiscountAmount }}</el-descriptions-item>
            <el-descriptions-item label="优惠券抵扣">{{ orderDetail.productCouponAmount }}</el-descriptions-item>
            <el-descriptions-item label="运费">{{ orderDetail.shippingAmount }}</el-descriptions-item>
            <el-descriptions-item label="运费减免">{{ orderDetail.freeShippingAmount }}</el-descriptions-item>
            <el-descriptions-item label="运费券抵扣">{{ orderDetail.shippingCouponAmount }}</el-descriptions-item>
            <el-descriptions-item label="实付">{{ orderDetail.orderActualAmount }}</el-descriptions-item>
            <el-descriptions-item label="退款" v-if="orderDetail.refund">{{ orderDetail.refundAmount }}</el-descriptions-item>
            <el-descriptions-item v-else />
          </el-descriptions>
        </el-card>
      </template>
      <template v-if="orderDetail.orderType === 'PRODUCT'">
        <el-card class="mt10">
          <el-descriptions
            title="基本信息"
            :column="2"
            border
            label-class-name="my-label"
            contentClassName="my-content">
            <template v-if="orderDetail.isGroupOrder === '1'">
              <el-descriptions-item label="订单ID">{{ orderDetail.orderId }}</el-descriptions-item>
              <el-descriptions-item label="订单类型">商品订单</el-descriptions-item>
              <el-descriptions-item label="是否拼单">是</el-descriptions-item>
              <el-descriptions-item label="下单手机号">{{ orderDetail.orderPhone }}</el-descriptions-item>
              <el-descriptions-item label="下单UID">{{ orderDetail.userId }}</el-descriptions-item>
              <el-descriptions-item label="下单时间">{{ timeFormat(orderDetail.placeOrderTime, '') }}</el-descriptions-item>
              <el-descriptions-item label="成团时间">{{ timeFormat(orderDetail.groupPayTime, '') }}</el-descriptions-item>
              <el-descriptions-item label="订单状态">{{ orderDetail.orderStatusDesc }}</el-descriptions-item>
              <el-descriptions-item label="发货时间">{{ timeFormat(orderDetail.shipmentTime, '') }}</el-descriptions-item>
              <el-descriptions-item label="订单内容">{{ orderDetail.productName }}</el-descriptions-item>
              <el-descriptions-item label="数量">{{ orderDetail.productQuantity }}</el-descriptions-item>
              <el-descriptions-item label="单价">{{ orderDetail.productPrice }}</el-descriptions-item>
              <el-descriptions-item />
            </template>
            <template v-else>
              <el-descriptions-item label="订单ID">{{ orderDetail.orderId }}</el-descriptions-item>
              <el-descriptions-item label="订单类型">商品订单</el-descriptions-item>
              <el-descriptions-item label="是否拼单">否</el-descriptions-item>
              <el-descriptions-item label="下单手机号">{{ orderDetail.orderPhone }}</el-descriptions-item>
              <el-descriptions-item label="下单UID">{{ orderDetail.userId }}</el-descriptions-item>
              <el-descriptions-item label="下单日期">{{ timeFormat(orderDetail.placeOrderTime, '') }}</el-descriptions-item>
              <el-descriptions-item label="订单状态">{{ orderDetail.orderStatusDesc }}</el-descriptions-item>
              <el-descriptions-item label="发货时间">{{ timeFormat(orderDetail.shipmentTime, '') }}</el-descriptions-item>
              <el-descriptions-item label="订单内容">{{ orderDetail.productName }}</el-descriptions-item>
              <el-descriptions-item label="数量">{{ orderDetail.productQuantity }}</el-descriptions-item>
            </template>
          </el-descriptions>
        </el-card>
        <el-card class="mt10">
          <el-descriptions title="收货信息" :column="3" border label-class-name="my-label" contentClassName="my-content">
            <el-descriptions-item label="收货地址">{{ addressArr.deliveryAddress }}</el-descriptions-item>
            <el-descriptions-item label="联系人">{{ addressArr.deliveryName }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ addressArr.contactNumber }}</el-descriptions-item>
          </el-descriptions>
        </el-card>
        <el-card class="mt-10">
          <el-descriptions title="物流信息" :column="2" border label-class-name="my-label" contentClassName="my-content">
            <el-descriptions-item label="运单号">{{ setshippingNoFn(addressArr.shippingWaybills) || '--'}}</el-descriptions-item>
            <el-descriptions-item label="物流公司">{{ addressArr.shippingCompany }}</el-descriptions-item>
          </el-descriptions>
        </el-card>
        <el-card class="mt10">
          <el-descriptions
            title="交易信息"
            :column="2"
            border
            size="small"
            label-class-name="my-label"
            contentClassName="my-content">
            <el-descriptions-item label="拼单价" v-if="orderDetail.isGroup">{{ orderDetail.productGroupBuyPrice }}</el-descriptions-item>
            <el-descriptions-item label="原价" v-else>{{ orderDetail.productPrice }}</el-descriptions-item>
            <el-descriptions-item label="优惠券抵扣">{{ orderDetail.productCouponAmount }}</el-descriptions-item>
            <el-descriptions-item label="运费">{{ orderDetail.shippingAmount }}</el-descriptions-item>
            <el-descriptions-item label="运费减免">{{ orderDetail.freeShippingAmount }}</el-descriptions-item>
            <el-descriptions-item label="运费券抵扣">{{ orderDetail.shippingCouponAmount }}</el-descriptions-item>
            <el-descriptions-item label="实付">{{ orderDetail.orderActualAmount }}</el-descriptions-item>
            <template v-if="orderDetail.isRefund">
              <el-descriptions-item label="退款金额">{{ orderDetail.refundAmount }}</el-descriptions-item>
              <el-descriptions-item />
            </template>
          </el-descriptions>
        </el-card>
      </template>
    </el-main>
  </div>
</template>

<script>
import { queryOrderDetail } from "@/api/order";
import { refundOrder } from "@/api/order";
import { getExpressOrder, sendExpressOrder } from "@/api/logistics";
import { numberToChinese } from '@/utils/numberToChinese';
import { mergePdfs } from "@/utils";

export default {
  data() {
    return {
      disabledRefundStatus: ['REFUNDED', 'CANCELED', 'PENDING_PAYMWENT', 'UNFINISHED_PAYMENT_CANCEL',
        'CANCEL_BEFORE_SHIPMENT', 'GROUP_ORDER_FAIL_CANCLE', 'CANCELED_REFUNDED'],
      products: [],
      numberToChinese,
      orderDetail: {
        type: 'product',
        // 是否拼团
        isGroup: false,
        isRefund: false
      },
      addressArr: {}, // 商品订单的地址
      addressPlanArr: {}, // 计划订单的地址
      loading: false
    }
  },
  created() {
    const { id } = this.$route.query
    this.queryDetail(id)
  },
  methods: {
    // 打印面单
    async handlePrint(shippingId) {
      const { code: orderCode, data } = await getExpressOrder([shippingId])
      if (orderCode !== 200) return this.$message.error('面单生成失败')
      if (!data.success) return this.$message.error(data.errorMessage)
      const files = data?.obj?.files || []
      const pdfUrl = await mergePdfs(files);
      const { code } = await this.$print(pdfUrl)
      if (code !== 200) this.$message.error('打印失败')
    },
    checkPrint(item) {
      return !item?.shippingWaybills?.length
    },
    timeFormat(timeStamp) {
      if(!timeStamp) return '--';
      return this.$moment(timeStamp).format('YYYY-MM-DD HH:mm:ss')
    },
    async queryDetail(id) {
      this.loading = true
      const { code, data } = await queryOrderDetail({ orderId: id })
      this.loading = false
      if (code !== 200) return;
      this.orderDetail = data;
      // 收获地址
      if(data.orderType === 'PRODUCT') {
        this.addressArr = data.shippingPojos[0];
      } else {
        this.addressPlanArr = data.shippingPojos;
      }
    },
    setshippingNoFn(data) {
      const newNumber = data?.map((item) => {
        return item.waybillNumber || item.sfOrder
      })
      return newNumber.join(',')
    },
    setShippingProductsFn(data) {
      const newNumber = data?.map((item) => {
        return `${item.productName}*${item.productNumber}`
      })
      return newNumber.join(',')
    },
    // 发货
    handleDelivery(shippingId) {
      this.$confirm('确定发货吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { code, msg } = await sendExpressOrder({ shippingId });
        if (code !== 200) return this.$message.error(msg)
        this.$message.success('发货成功')
        const { id } = this.$route.query
        return this.queryDetail(id)
      }).catch()
    },
     // 退款
     handleRefund(orderId) {
       let refundableAmount = 0;
       
       if (this.orderDetail.orderType === 'PLAN') {
         // 计划订单退款逻辑
         const totalAmount = this.orderDetail.orderActualAmount; // 实付金额
         const totalPeriods = this.orderDetail.planInfoPojo.deliveryTimes; // 总期数
         const undeliveredPeriods = this.orderDetail.shippingPojos.filter(item => 
           item.shippingStatus === 'PENDING_SHIPMENT'
         ).length; // 未配送期数
         
         // 计算可退金额 = 实付金额 / 总期数 * 未配送期数
         refundableAmount = totalAmount / totalPeriods * undeliveredPeriods;
       } else if (this.orderDetail.orderType === 'PRODUCT') {
         // 商品订单退款逻辑
         refundableAmount = this.orderDetail.orderActualAmount;
       }
       
       // 当计算得出的退款金额≤0时，展示的可退款金额=0
       refundableAmount = Math.max(0, Number(refundableAmount.toFixed(2)));
   
       this.$prompt(`可退款金额：¥${refundableAmount}\n请输入退款金额`, '提示', {
         confirmButtonText: '确定',
         cancelButtonText: '取消',
         inputPattern: /^\d+(\.\d{1,2})?$/,
         inputErrorMessage: '金额格式不对'
       }).then(async ({ value }) => {
         if (!value) return;
         if (value > this.orderDetail.orderActualAmount) return this.$message.error('退款金额不能大于订单实付金额')
         const { code, msg } = await refundOrder({ orderId, refundAmount: value })
         if (code !== 200) return this.$message.error(msg)
         const { id } = this.$route.query
         this.queryDetail(id)
         return this.$message.success('退款成功')
       }).catch()
     },
    getOrderStatus(row) {
      return ''
    },
    getPayType(row) {
      return ''
    }
  }
}
</script>

<style lang="stylus">
.order_detail_wrapper
  > .el-card + .el-card
    margin-top 1rem

  .el-form-item
    margin-bottom 0

    .el-form-item__content, .el-form-item__label
      line-height 2

.my-label
  width 100px

.my-content
  width 400px

.popperOptions[x-placement^=left] .popper__arrow::after {
  border-left-color: #565D6B;
}
.vertical {
  display flex;
  flex-direction column;
  gap: 10px
}
.popperOptions[x-placement^=right] .popper__arrow::after {
  border-right-color: #565D6B;
}

.popperOptions[x-placement^=bottom] .popper__arrow::after {
  border-bottom-color: #565D6B;
}

.popperOptions[x-placement^=top] .popper__arrow::after {
  border-top-color: #565D6B;
}

.popperOptions {
  background-color: #565D6B;
  color: #FFFFFF;
  border: #565D6B;
}

.el-timeline-item__content {
  color: #fff;
}

.el-timeline-item__timestamp {
  color: #fff;
}
</style>
